#include <QDeclarativeView>
#include <QDeclarativeEngine>
#include <QDeclarativeContext>
#include <QtDebug>
#include "widget.h"
#include "ui_widget.h"


Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    m_mapProvider = "init.html";
    ui->setupUi(this);
    m_view = new QDeclarativeView(this);
    m_view->rootContext()->setContextProperty("cppEngine", this);
    m_view->setSource(QUrl("qrc:/qmls/main.qml"));
    ui->verticalLayout->addWidget(m_view);
    m_view->setResizeMode(QDeclarativeView::SizeRootObjectToView);

    ui->comboBox->addItem("Select Map Provider", QVariant("init.html"));
    ui->comboBox->addItem("OVI Maps", QVariant("ovimaps.html"));
    ui->comboBox->addItem("Google Maps", QVariant("gmaps.html"));
    ui->comboBox->addItem("Bing Maps", QVariant("bingmaps.html"));

    m_geoSource = QGeoPositionInfoSource::createDefaultSource(this);

    if (m_geoSource)
    {
        connect(m_geoSource, SIGNAL(positionUpdated(QGeoPositionInfo)), this, SLOT(positionUpdated(QGeoPositionInfo)));
        m_geoSource->setUpdateInterval(10000);
        m_geoSource->startUpdates();
    }

    connect(ui->comboBox, SIGNAL(currentIndexChanged(int)),
            this, SLOT(mapProviderSelected(int)));
}


Widget::~Widget()
{
    delete ui;
}

QString Widget::mapProvider()
{
    return m_mapProvider;
}

void Widget::mapProviderSelected(int index)
{
    QString htmlFileName = ui->comboBox->itemData( index ).toString();
    setMapProvider( htmlFileName );
}

void Widget::setMapProvider(QString newMapProvider)
{
    if (m_mapProvider == newMapProvider)
        return;
    else
    {
        m_mapProvider = newMapProvider;
        emit mapProviderChanged(m_mapProvider);
    }
}

void Widget::positionUpdated(QGeoPositionInfo info)
{
    emit posUpdated( info.coordinate().latitude(), info.coordinate().longitude());
}
